<?php


namespace app\admin\logic\system;

use app\admin\logic\BaseLogic;
use app\common\model\system\SysMenu;
use app\common\model\system\SysMenuApi;
use app\common\model\system\SysRoleMenu;
/**
 * 系统管理员逻辑
 * Class SysMenuLogic
 * @package app\admin\logic\system
 */
class SysMenuLogic extends BaseLogic
    {

    /**
     * @notes  查看系统管理员详细信息
     * @param $adminInfo
     * @return array
     * @author heshihu
     * @date 2022/2/22 10:15
     */
    public static function getMenuByAdminId($adminInfo) : array
    {
        $roleMenu = SysRoleMenu::where('role_id', 'in', $adminInfo->role_id)->with(['mate'])->column('menu_id');
        $where = [ 
            ['type', 'in', ['menu']],
            ['hidden', '=', 0],
            ['id', 'in', $roleMenu]
        ];
        $showField = self::showFields();
        $menu = SysMenu::where($where)->field($showField)->order('sort asc')->select();
        $menus = [];
        foreach ($menu as $item) {
            $menus[] = [
                'id' => $item->id,
                'parent_id' => $item->parent_id,
                'name' => $item->name,
                'path' => $item->path,
                'component' => $item->component,
                'redirect' => $item->redirect,
                'meta' =>self::meta($item),
            ];
        }
        return linear_to_tree($menus, 'children', 'id', 'parent_id');

    }
    public static function showFields(){
        return ['id', 'parent_id', 'name', 'path', 'component', 'redirect', 'title','hidden', 'affix', 'icon', 'type','active', 'color', 'fullpage', 'hidden_breadcrumb'];
    }
    /**
     * 列表tree
     * @param array $param
     */
    public static function lists(array $param): array
    {
        $list = SysMenu::with(['apiList'])->order('sort asc, id desc')
            ->select();

        $menus = [];
        foreach ($list as $item) {
            $menus[] = [
                'id' => $item->id,
                'parent_id' => $item->parent_id,
                'name' => $item->name,
                'path' => $item->path,
                'apiList' => $item->apiList,
                'component' => $item->component,
                'redirect' => $item->redirect,
                'sort' => $item->sort,
                'meta' => self::meta($item),
            ];
        }
        return linear_to_tree($menus, 'children', 'id', 'parent_id');
    }
    /**
     * 生成菜单元数据
     * @param SysMenu $menu
     * @return array
     */
    private static function meta(SysMenu $menu): array
    {
        return [
            'title' => $menu->title,
            'hidden' => $menu->hidden,
            'affix' => $menu->affix,
            'icon' => $menu->icon,
            'type' => $menu->type,
            'hidden_breadcrumb' => $menu->hidden_breadcrumb,
            'active' => $menu->active,
            'color' => $menu->color,
            'fullpage' => false,
            'query'=>$menu->params,
        ];
    }
    /**
     * 菜单编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): int
    {
        $auth = $this->auth;
        $menu = new SysMenu();
        $data['id'] = $id==9999999999?'':$id;
        self::showTips($menu,$data['id'],'菜单不存在');
        $data['id']? $data['updated_by'] = $auth->username:$data['created_by'] = $auth->username;
        $meta = $data['meta'];
        $data['title'] = $meta['title'];
        $data['type'] = $meta['type'];
        if ($meta['type']!= 'button') {
            $data['icon'] = $meta['icon'];
            $data['affix'] = $meta['affix'];
            $data['color'] = $meta['color'];
            $data['active'] = $meta['active'];
            $data['hidden'] = $meta['hidden']? 1 : 0;
            $data['hidden_breadcrumb'] = $meta['hidden_breadcrumb']? 1 : 0;
            $data['fullpage'] = $meta['fullpage']? 1 : 0;
        }
        $res = $data['id']?SysMenu::update($data):SysMenu::create($data);
        if (!$res) {
            tips('保存失败');
        }
        $role=SysRoleMenu::where(['role_id'=>1,'menu_id'=>$res->id])->find();
        if(empty($role) && $res->id){
            $role=new SysRoleMenu();
            $role->role_id=1;
            $role->menu_id=$res->id;
            $role->save();
        }
        self::saveApiList($data['apiList'],$res->id);
        return (int)$res->id;
    }
    public static function saveApiList($data,$menuId){
        // 菜单接口
        $sysMenuApi = new  SysMenuApi;
        $sysMenuApi->where('menu_id', $menuId)->delete();
        $apiList = [];
        foreach ($data as $api) {
            $apiList[] = [
                'menu_id' =>$menuId,
                'code' => trim($api['code']),
                'url' => trim($api['url']),
                'api_method' => $api['api_method'],
                'is_record' => $api['is_record']
            ];
        }
        if ($apiList) {
            $sysMenuApi->saveAll($apiList);
        }
        return true;
    }
    /**
     * 删除菜单
     * @param array $ids
     */
    public function delete(array $ids): void
    {
        if (!$ids) {
            tips('无菜单信息');
        }
        foreach ($ids as $id) {
            SysMenu::destroy($id);
            $this->_deleteChildren((int) $id);
        }
    }
    /**
     * 删除下级菜单
     * @param integer $parent_id
     */
    protected function _deleteChildren(int $parent_id): void
    {
        $children = SysMenu::where('parent_id', $parent_id)->select();
        foreach ($children as $menu) {
            SysMenu::destroy($menu->id);
            $this->_deleteChildren($menu->id);
        }
    }
    /**
     * 获取角色菜单接口
     * @param Array $role_id 角色id
     * @param string $type code只获取接口标识
     */
    public static function roleMenuApi(Array $role_id, $type = ''): array
    {
        $apilist = SysRoleMenu::alias('rm')
            ->field('ma.code,ma.url,ma.api_method')
            ->join('la_system_menu_api ma', 'ma.menu_id=rm.menu_id')
            ->whereIn('rm.role_id', $role_id)
            ->select();
        // 接口标识
        if ($type == 'code') {
            $result = [];
            foreach ($apilist as $item) {
                if ($item->code) {
                    $result[] = $item->code;
                }
            }
            return $result;
        }
        return $apilist->toArray();
    }

}